package main

import (
	"context"
	"github.com/hashicorp/consul/api"
	pb "grpc-demo/out_pb"
	"log"
	"strconv"

	"google.golang.org/grpc"
)

func main() {
	consulConfig := api.DefaultConfig()
	consulClient, err := api.NewClient(consulConfig)
	if err != nil {
		log.Println("创建 consul 对象失败:", err)
	}

	// 服务发现，从 consul 上获取健康服务
	services, _, err2 := consulClient.Health().Service("MakiFirstService", "TagC", true, nil)
	if err2 != nil {
		log.Println("无法发现服务:", err)
	}

	addr := services[0].Service.Address + ":" + strconv.Itoa(services[0].Service.Port)

	// 用 grpc 连接服务器，并且添加 grpc.WithInsecure()，不然没有证书会报错
	// conn, err := grpc.Dial("localhost:7001", grpc.WithInsecure())

	// 使用服务发现 consul 上的 IP/port 来与服务建立连接
	conn, err := grpc.Dial(addr, grpc.WithInsecure())
	if err != nil {
		log.Println("连接失败：", err)
		return
	}
	defer conn.Close()

	// 调用 *.pb.go中的 New*Client 方法
	client := pb.NewUserCenterClient(conn)
	nClient := pb.NewNoticeCenterClient(conn)

	// 以下测试
	ctx := context.Background()

	id := Register(ctx, client)

	if id != "" {
		log.Println("注册成功，用户Id: " + id)

		ToEmail(ctx, nClient, "测试人员1", "test001@163.com", "你好，这是一封测试邮件，请勿理会")
		Login(ctx, client, id)
	} else {
		log.Println("注册失败")
	}
}

// Register 注册
func Register(ctx context.Context, client pb.UserCenterClient) (id string) {
	user := pb.User{}
	user.Username = "测试用户1"
	user.Password = "123456"
	user.Email = "lindon446@gmail.com"
	aUser := pb.RegisterRequest{User: &user}

	result, err := client.Register(ctx, &aUser)
	if err != nil {
		log.Println("注册失败：", err)
		return
	}
	return result.UserId
}

func Login(ctx context.Context, client pb.UserCenterClient, id string) {
	p, err := client.Login(ctx, &pb.LoginRequest{UserId: id})
	if err != nil {
		log.Println("登录失败：", err)
		return
	}
	log.Printf("登录成功， : %+v\n", p)
}

func ToEmail(ctx context.Context, client pb.NoticeCenterClient, username string, email string, content string) {
	p, err := client.ToEmail(ctx, &pb.EmailRequest{Username: username, Email: email, Content: content})
	if err != nil {
		log.Println("发送失败：", err)
		return
	}
	log.Printf("发送成功， : %+v\n", p)
}
